﻿using System;
using System.IO;
using System.Linq;
using CustomerContactSystem.Core.Model;

namespace CustomerContactSystem.WebForms.Enquiries.Documents {
    public partial class Create : BasePage {
        protected void Page_Load(object sender, EventArgs e) {
            if (!IsValidPageRequest(true, true, "id")) {
                return;
            }

            EnquiryIdCaption.Text = Request.QueryString["id"];
            EnquiryIdCaption.NavigateUrl = "~/Enquiries/View.aspx?id=" + Request.QueryString["id"];

            GetUsers();
        }

        private void GetUsers() {
            var users = UserRepository.QueryOver().Where(u => u.IsActive).OrderBy(u => u.DisplayName).Asc.List();
            BindDropDownList(OtherUsers, users, "DisplayName", "Id", "--Select--", "0");
        }

        protected void SubmitDocumentClick(object sender, EventArgs e) {
            if (!IsValidPageRequest(true, false, "id")) {
                return;
            }

            var enquiryId = int.Parse(Request.QueryString["id"]);
            var enquiry = EnquiryRepository.GetById(enquiryId);

            if (enquiry == null) {
                SubmitDocumentResultMessage.Text = "Error enquiry not found!";
                return;
            }

            User otherUser = null;
            if (OtherUsers.SelectedIndex > 0) {
                otherUser = UserRepository.GetById(int.Parse(OtherUsers.SelectedItem.Value));
            }

            var fileName = GetUploadedFileName();
            var fileExtension = fileName.Substring(fileName.LastIndexOf(".", StringComparison.Ordinal) + 1).ToLower();
            var newFileName = Guid.NewGuid() + "." + fileExtension;
            var docsFolder = ConfigSettings.DocumentsFolder;
            var siteRoot = ConfigSettings.SiteRoot;
            var documentRoot = siteRoot + docsFolder;
            var viewUrl = ConfigSettings.SiteRoot + "Enquiries/View.aspx?id=" + enquiryId;
            var document = enquiry.AddDocument(LoggedUser, DocumentName.Text, DocumentDescription.Text,
                                               NotifySubmitter.Checked, otherUser, viewUrl, documentRoot, fileExtension);

            if (!IsValidObject(document, SubmitDocumentResultMessage)) {
                return;
            }

            if (!IsValidUpload()) {
                return;     
            }

            var saveFolder = Server.MapPath("~/Docs" + document.SavePath());
            if (!Directory.Exists(saveFolder)) {
                Directory.CreateDirectory(saveFolder);
            }

            DocumentFile.PostedFile.SaveAs(Server.MapPath("~/Docs/" + document.SavePath() + newFileName));
            
            EnquiryRepository.Update(enquiry);
            
            Response.Redirect("~/Enquiries/View.aspx?id=" + enquiry.Id);
        }

        private bool IsValidUpload() {
            if (DocumentFile.PostedFile == null || DocumentFile.PostedFile.ContentLength == 0) {
                SubmitDocumentResultMessage.Text = "Please chose a file to uplad!";
                return false;
            }

            var fileName = GetUploadedFileName();
            var fileExtension = fileName.Substring(fileName.LastIndexOf(".", StringComparison.Ordinal) + 1).ToLower();
            var allowedExtensions = ConfigSettings.AllowedFileExtensions.Split(',');

            return allowedExtensions.Any(allowedExtension => allowedExtension == fileExtension);
        }

        private string GetUploadedFileName() {
            var fileName = DocumentFile.PostedFile.FileName;
            return fileName.Substring(fileName.LastIndexOf("\\", StringComparison.Ordinal) + 1);
        }
    }
}